package myJs.api

import myJs.myPkg.MyFetch
import myJs.tool.Tool
import org.scalajs.dom.{FormData, XMLHttpRequest}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import upickle.default._

/**
 * Created by yz on 19/5/2022
 */
object TestApi {

  val baseUrl = s"${Api.apiUrl}/panda/test"

  import shared.pojo.Test._

  def all = {
    val account = Tool.getAccount
    val url = s"${baseUrl}/all?account=${account}"
    MyFetch.getRnStr(url = s"${url}", headers = Map("Content-Type" -> "application/json")).map { str =>
      read[List[ujson.Obj]](str)
    }
  }

  def dbAll = {
    val url = s"${baseUrl}/dbAll"
    MyFetch.getRnStr(url = s"${url}", headers = Map("Content-Type" -> "application/json")).map { str =>
      read[List[ujson.Obj]](str)
    }
  }

  def getById(idV: String) = {
    val url = s"${baseUrl}/getById"
    MyFetch.getRnStr(url = s"${url}?id=${idV}", headers = Map("Content-Type" -> "application/json")).map { str =>
      val data = read[TestInfoData](str)
      data
    }
  }

  def get(request: Get.Request) = {
    val url = s"${baseUrl}/get"
    MyFetch.postRnText(url = s"${url}", data = write(request), headers = Map("Content-Type" -> "application/json")).
      map { str =>
      val data = read[TestInfoData](str)
      data
    }
  }

  def updateWorkflow(formData: FormData)(f: String => Unit) = {
    val url = s"${baseUrl}/updateWorkflow"
    val xhr = new XMLHttpRequest
    xhr.open("post", url)
    xhr.onreadystatechange = (e) => {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        val response = xhr.responseText
        f(response)
      }
    }
    xhr.send(formData)
  }


}
